//
// Created by denglibin on 19-10-29.
//
/***
 *
 * 本地套接字 服务端
 * */

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <ctype.h>
#include <strings.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stddef.h>
#include "wrap.h"
#define SERV_ADDR "foo.socket"

static int main_(void){
    int lfd, cfd, len, size, i;
    struct sockaddr_un server_addr, client_addr;
    char buf[4096];

    lfd = Socket(AF_UNIX, SOCK_STREAM, 0);
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sun_family = AF_UNIX;
    strcpy(server_addr.sun_path, SERV_ADDR);
    len = offsetof(struct sockaddr_un, sun_path) + strlen(server_addr.sun_path);

    /*有该文件的话先删除文件*/
    unlink(SERV_ADDR);
    Bind(lfd, (struct sockaddr*) &server_addr, len);
    Listen(lfd, 20);
    while (1){
        len = sizeof(client_addr);
        cfd = Accept(lfd, (struct sockaddr *)&client_addr, &len);
        len -= offsetof(struct sockaddr_un, sun_path);
        printf("client bind filename %s\n", client_addr.sun_path);
        while ((size = read(cfd, buf, sizeof(buf))) > 0){
            for(i = 0; i < size; i++){
                buf[i] = toupper(buf[i]);
            }
            write(cfd, buf, size);
        }
        close(cfd);
        break;
    }
    close(lfd);

    return 0;
}